import axios from 'axios'
var qs = require('qs');
import stroe from '../../store/index'
import router from '../../router/index'

// request 拦截器
axios.interceptors.request.use(config => {
  // let token = sessionStorage.getItem('token')
  // if (token) {
  //   config.headers['Authorization'] = `${token}`
  // }
  return config
}, error => {
  return Promise.reject(error)
})

// response 拦截器
axios.interceptors.response.use(response => {
  if (!response.data){
    return Promise.reject(response)
  } else{
    return response
  }
}, error => {
  return Promise.reject(error)
}) 

// 封装get请求
export function Get (url, params = {}, withCredentials = false, isLoading = true) {
  let loadingInstance
  axios.defaults.timeout = 300000
  if (isLoading) {
    loadingInstance = loading()
  }
  if (params.isService) {
    axios.defaults.baseURL = 'http://cs.ashhclub.com/'  
    // axios.defaults.baseURL = 'http://qyvx-api.ashhclub.com/'
  } else {
    axios.defaults.baseURL = 'http://127.0.0.1:19257'
  }
  delete params.isService
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params,
      headers: {
        'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      }
    }, {withCredentials: withCredentials}).then(response => {
      isLoading && loadingInstance.close()
      resolve(response.data)
    }).catch(error => {
      isLoading && loadingInstance.close()
      reject(error)
    })
  })
}

// 封装post请求
export function Post (url, params = {}, config = {}, isLoading = true) {
  let loadingInstance
  axios.defaults.timeout = 300000
  if (isLoading) {
    loadingInstance = loading()
  }
  if (params.isService || url.includes('api/soft-ware/user-info/save')) {
    axios.defaults.baseURL = 'http://cs.ashhclub.com/'
    // axios.defaults.baseURL = 'http://qyvx-api.ashhclub.com/'
  } else {
    axios.defaults.baseURL = 'http://127.0.0.1:19257'
  }
  delete params.isService
  let data
  if(!url.includes('api/soft-ware/user-info/save')){
    data = qs.stringify(params)
  }else{
    data =  params
  }
  return new Promise((resolve, reject) => {
    axios.post(url, data, config).then(response => {
      if(response){
        isLoading && loadingInstance.close()
        resolve(response.data)
      }
    }).catch(error => {
      isLoading && loadingInstance.close()
      reject(error)
    })
  })
}

export {
  axios
}
